from django.shortcuts import render, redirect
# 导包
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
# 导入类视图
from django.views import View
import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
# 导入加密库
import hashlib
# 导入图片库
# 绘画库
from PIL import ImageDraw
# 字体库
from PIL import ImageFont
# 图片库
from PIL import Image
# 随机库
import random
# 文件流
import io

import requests

# 导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os

# 导入原生sql模块
from django.db import connection

import jwt

# 导入redis数据库
import redis

# 导入时间模块
import time

# 导入公共目录变量
from mydjango.settings import BASE_DIR

# 导包
from django.db.models import Q, F

# 导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid
# 导入表
from myapp.models import *
# 导包
import redis
# 导入中间件
from django.utils.deprecation import MiddlewareMixin

from myapp.myser import CarouserlSer
from myapp.myser import *
# 定义ip端口
host = "localhost"
port = 6379
# 建立连接
r = redis.Redis(host=host, port=port)

#商品评论获取
class CommentList(APIView):
    def get(self,request):
        gid=request.GET.get('gid')
        #查询数据,根据新的评论，在前展示
        comments=Comment.objects.filter(gid=gid).order_by('-id')
        #序列化
        comment_ser=CommentSer(comments,many=True)
        data=comment_ser.data
        return Response(data)




# 商品评论
class CommentInsert(APIView):
    def post(self,request):
        #获取客户端ip阻止爬虫,hhhh
        if 'HTTP_X_FORWARDED_FOR' in request.META:
            # 这个是为了规避代理ip
            ip = request.META.get('HTTP_X_FORWARDED_FOR')
        else:
            ip = request.META.get('REMOTE_ADDR')
        print(ip)
        if r.llen(ip)>3:
            return Response({'code':403,'message':'您评论过快'})


        #序列化，初始化参数
        comment = CommentSer(data=request.data)
        # 验证字段
        if comment.is_valid():
            #入库操作
            comment.save()
            #设置评论间隔时间,key值拿ip ，value随便
            #添加一个值，每次评论，这个值加一，通过判断长度来约束评论次数

            r.lpush(ip,1)
            r.expire(ip,30)
            return Response({"code":200,'message':'评论成功'})




class GoodsInfo(APIView):
    def get(self, request):
        id = request.GET.get('id')

        # 查询
        good = Goods.objects.get(id=id)
        good_ser = GoodsSer(good)
        return Response(good_ser.data)


# 变态搜索
class Search(APIView):
    def get(self, request):
        text = request.GET.get('text')
        # 转换数据类型 json 转字符串
        text = json.loads(text)
        sql = ''
        # 动态拼接
        for val in text:
            sql += "or name like'%%s%%'" % val

        # 建立游标对象
        cursor = connection.cursor()
        # 执行sql
        cursor.execute("select name,price from goods where id!=0 and "+sql)

        # 查询
        # result = cursor.fetchall()
        result = dictfetch(cursor)
        print(result)

        print(text)

        return Response({})


# 格式化结果集
def dictfetch(cursor):
    # 声明描述符
    # 声明描述符
    desc = cursor.description

    return [dict(zip([col[0] for col in desc], row))

            for row in cursor.fetchall()
            ]


# 商品列表页+搜索
class GoodsList(APIView):
    def get(self, request):
        # //排序字段
        coloum = request.GET.get('coloum')
        # 排序方案
        sort_order = request.GET.get('order')
        # 获取当前页，默认第一页
        page = request.GET.get('page', 1)
        text = request.GET.get('text')
        print(text)
        # 一夜显示多少个数
        size = request.GET.get('size', 1)
        # 计算从哪开始切
        data_start = (int(page) - 1) * int(size)
        # 计算切到那儿
        data_end = int(page) * int(size)
        #
        if coloum:
            goods = Goods.objects.all().order_by(sort_order + coloum)[data_start:data_end]

        else:
            goods = Goods.objects.all()[data_start:data_end]
        # 判断是否进行模糊查询
        if text:
            goods = Goods.objects.filter(Q(name__contains=text) | Q(desc__contains=text))[data_start:data_end]
            count = Goods.objects.filter(Q(name__contains=text) | Q(desc__contains=text)).count()
        else:

            # 查询 切片操作
            # goods=Goods.objects.all()[data_start:data_end]
            # 查询所有商品个数
            count = Goods.objects.count()
        # 序列
        goods_ser = GoodsSer(goods, many=True)
        return Response({"code": 200, "message": goods_ser.data, 'total': count})


# 商品分类接口
class CategoryList(APIView):

    def get(self, request):
        category = Category.objects.all()

        print(category)
        ser = CategoryserlSer(category, many=True)
        dic = ser.data
        return Response({'code': 200, 'dic': dic})


# 商品入库
class InsertGoods(APIView):
    def post(self, request):
        print(request)
        name = request.POST.get('name')
        print(name)
        price = request.POST.get('price')
        params = request.POST.get('params')
        selected = request.POST.get('selected')
        print(selected)
        print(params)
        goods = Goods.objects.filter(name=name).first()
        cid = Category.objects.filter(name=selected).first().id
        print('这个主键ID是', cid)
        if goods:
            return Response({"code": 403, 'message': '您已经添加过该商品'})
        # 入库
        goods = Goods(name=name, price=price, params=params, cid_id=cid)
        goods.save()
        return Response({'code': 200, 'message': '商品添加成功'})
